// 这个脚本会在NW.js运行时执行，用于修复网络连接问题
(function() {
  // 检测是否在NW.js环境中运行
  if (typeof nw !== 'undefined') {
    console.log('正在NW.js环境中运行，应用网络访问修复');
    
    // 添加CORS请求头
    const originalFetch = window.fetch;
    window.fetch = function(url, options) {
      // 如果是相对URL且不包含完整协议，则添加基础URL
      if (typeof url === 'string' && !url.startsWith('http') && !url.startsWith('data:') && !url.startsWith('blob:')) {
        if (url.startsWith('/')) {
          url = 'http://localhost:8080' + url;
        } else {
          url = 'http://localhost:8080/' + url;
        }
      }
      
      options = options || {};
      options.headers = options.headers || {};
      options.mode = 'cors';
      options.credentials = 'include';
      return originalFetch(url, options);
    };
    
    // 添加XHR CORS支持
    const originalXhrOpen = XMLHttpRequest.prototype.open;
    XMLHttpRequest.prototype.open = function(method, url, async, user, password) {
      // 如果是相对URL且不包含完整协议，则添加基础URL
      if (typeof url === 'string' && !url.startsWith('http') && !url.startsWith('data:') && !url.startsWith('blob:')) {
        if (url.startsWith('/')) {
          url = 'http://localhost:8080' + url;
        } else {
          url = 'http://localhost:8080/' + url;
        }
      }
      
      this.withCredentials = true;
      return originalXhrOpen.call(this, method, url, async, user, password);
    };
    
    // 修复 Audio 元素
    const originalAudio = window.Audio;
    window.Audio = function() {
      const audio = new originalAudio();
      
      // 修改 src 属性的设置行为
      const originalSrcDescriptor = Object.getOwnPropertyDescriptor(HTMLMediaElement.prototype, 'src');
      if (originalSrcDescriptor && originalSrcDescriptor.set) {
        const originalSet = originalSrcDescriptor.set;
        
        Object.defineProperty(audio, 'src', {
          get: function() {
            return originalSrcDescriptor.get.call(this);
          },
          set: function(url) {
            // 如果是相对URL且不包含完整协议，则添加基础URL
            if (typeof url === 'string' && !url.startsWith('http') && !url.startsWith('data:') && !url.startsWith('blob:')) {
              if (url.startsWith('/')) {
                url = 'http://localhost:8080' + url;
              } else {
                url = 'http://localhost:8080/' + url;
              }
            }
            return originalSet.call(this, url);
          },
          enumerable: true,
          configurable: true
        });
      }
      
      // 创建自动重试机制
      audio.addEventListener('error', function(e) {
        console.warn('音频加载错误，正在尝试重新加载:', e);
        const currentSrc = audio.src;
        if (currentSrc && !currentSrc.startsWith('data:')) {
          setTimeout(function() {
            audio.src = currentSrc;
          }, 1000);
        }
      });
      
      return audio;
    };
    
    console.log('网络访问修复已应用');
  }
})(); 